<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserRegister;
use App\Http\Requests\UserLoginRequest;
use App\Model\User;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Controllers\Api\CommonApi;



class UserApi extends Controller
{
    //登录处理
    public function handlerSignIn(UserLoginRequest $request)
    {
    	$name = $request->input('name');
    	$pass = $request->input('pass');

    	$user = User::select(['name','id','pass'])->where('name',$name)->first();

    	if(!$user) {

    		//用户名不存在
    		return $this->json(1404,'用户名不存在');

    	}
        
    	//验证密码
    	if($pass == $user->pass) {
    		
    		//将用户信息存放到session
    		return $this->json(1200,'登录成功');
    	}

    	return $this->json(1401,'密码错误');
    }


    //处理注册
    public function json($code,$msg,$data = []) 
    {
    	return response()->json([
             'status' =>$code,
             'msg' => $msg,
             'data' =>$data,
    		]);
    }

    public function handlerRegister(UserRegister $request)

    {
    	$name = $request->input('name');
    	$pass = $request->input('pass');
        $code = $request->input('code');

        //验证码是否正确
        $bool = CommonApi::CheckCode($request, 'code');

        if(!$bool){
            
            return $this->json(1111,'验证码错误');
        } 

    	$user = User::select(['id','name','pass'])->where('name',$name)->first();

    	if($user) {
    		return $this->json(1404,'用户已存在');
    	}

    	$bool = User::insert([

    		'name'=>$name,
    		'pass'=>$pass,

    		]);

    	if($bool) {
            
    		return $this->json(1200,'注册成功');

    	}

    	return $this->json(1402,'注册失败');
    }
}

